package com.example.pei.papa.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;

import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.pei.papa.R;
import com.example.pei.papa.listener.compressPicturesListener;
import com.example.pei.papa.tables.AlumniCircle;
import com.example.pei.papa.task.compressPicturesTask;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadBatchListener;

import cn.pedant.SweetAlert.SweetAlertDialog;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;

public class addDynamic_Activity extends AppCompatActivity{

   // private RecyclerView mRecycleView;

    //private PhotoPickerAdapter photoAdapter;

    private ArrayList<String> selectedPhotos = new ArrayList<>();

    private Button button_addDynamic;
    private Button button_back;
    private EditText editText_content;

    private String userName;
    private String content;
    private String userPhone;
    private int    userSex;

    private AlumniCircle alumniCircle;
    private String objectId;

    private SweetAlertDialog sweetAlertDialog ;

    private GridView gv;
    private int columnWidth;
    private GridAdapter gridAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_add_dynamic_);





        sweetAlertDialog=new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        userName=getIntent().getStringExtra("username");
        userPhone=getIntent().getStringExtra("userphone");
        userSex=getIntent().getIntExtra("usersex",1);
        initUI();
     //   photoAdapter = new PhotoPickerAdapter(this, selectedPhotos);
//        mRecycleView.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
 //       mRecycleView.setAdapter(photoAdapter);


        gv = (GridView) findViewById(R.id.gv);
        //得到GridView中每个ImageView宽高
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        gv.setNumColumns(cols);
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int columnSpace = getResources().getDimensionPixelOffset(R.dimen.space_size);
        columnWidth = (screenWidth - columnSpace * (cols-1)) / cols;
        gridAdapter = new GridAdapter();
        gv.setAdapter(gridAdapter);

        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
             //   Toast.makeText(addDynamic_Activity.this,selectedPhotos.get(position)+" ~",Toast.LENGTH_SHORT).show();
                if (gridAdapter.getItemViewType(position) == gridAdapter.TYPE_ADD) {
                            PhotoPicker.builder()
                                    .setPhotoCount(gridAdapter.MAX)
                                    .setShowCamera(true)
                                    .setPreviewEnabled(false)
                                    .setSelected(selectedPhotos)
                                    .start(addDynamic_Activity.this);
                        } else {
                            PhotoPreview.builder()
                                    .setPhotos(selectedPhotos)
                                    .setCurrentItem(position)
                                    .start(addDynamic_Activity.this);
                        }

            }
        });


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK &&(requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {
            List<String> photos = null;
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            }
            selectedPhotos.clear();

            if (photos != null) {
                selectedPhotos.addAll(photos);
                //刷新
                gridAdapter.notifyDataSetChanged();
                //设置按钮的样式
                if(photos.size()>0) {
                    button_addDynamic.setTextColor(Color.parseColor("#ffffff"));
                    button_addDynamic.setClickable(true);
                }else if(isAllSpace(editText_content.getText().toString())){
                    button_addDynamic.setTextColor(Color.parseColor("#a2a2a2"));
                    button_addDynamic.setClickable(false);
                }
            }

        }
    }

    private void initUI(){
        //找到导航栏
        RelativeLayout title=(RelativeLayout)findViewById(R.id.add_dynamic_include);
        button_addDynamic=(Button)title.findViewById(R.id.btn_add);
        button_addDynamic.setTextColor(Color.parseColor("#a2a2a2"));

        button_back=(Button)title.findViewById(R.id.button_backward);
        editText_content=(EditText)findViewById(R.id.et_content);
        button_back.setText("取消");
        TextView textView=(TextView)findViewById(R.id.text_title) ;
        textView.setText("发技能");
        button_addDynamic.setText("发表");

        editText_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                content=editText_content.getText().toString();
                if(isAllSpace(content)&&selectedPhotos.size()==0){
                    button_addDynamic.setTextColor(Color.parseColor("#a2a2a2"));
                    button_addDynamic.setClickable(false);
                }else
                {
                    button_addDynamic.setTextColor(Color.parseColor("#ffffff"));
                    button_addDynamic.setClickable(true);
                }
            }
        });

        button_addDynamic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                button_addDynamic.setClickable(false);
                content=editText_content.getText().toString();
                //加载开始
                sweetAlertDialog.show();

                alumniCircle=new AlumniCircle();
                alumniCircle.setSenderID(userName);
                alumniCircle.setContent(content);
                alumniCircle.setSenderPhone(userPhone);
                alumniCircle.setSex(userSex);


                if(selectedPhotos.size()==0){
                    alumniCircle.setPhotoNumber(0);
                }else{
                    alumniCircle.setPhotoNumber(-1);   //-1代表不是正常的数值，后面上传成功则不会为-1
                }


                //创建一条记录
                alumniCircle.save(new SaveListener<String>() {
                    @Override
                    public void done(final String objectid, BmobException e) {
                        if(e==null){
                            objectId=objectid;
                            int photoNum=selectedPhotos.size();
                            //如果添加动态成功，则开始添加图片信息
                            final String[] filePaths = new String[photoNum];
                            for(int i=0;i<photoNum;i++){
                                filePaths[i]=selectedPhotos.get(i);
                            }
                            if(photoNum!=0){ //有图片需要上传
                                compressPictures(filePaths);
                            }else{
                                //没有图片需要上传则可以直接结束活动
                                Intent intent = new Intent();
                                intent.putExtra("data_return", "success");
                                setResult(RESULT_OK, intent);

                                //progress取消显示
                                sweetAlertDialog.dismiss();
                                finish();

                            }

                        }else {
                            Toast.makeText(addDynamic_Activity.this,"sorry...创建失败了",Toast.LENGTH_LONG).show();
                            sweetAlertDialog.dismiss();
                            button_addDynamic.setClickable(true);
                        }
                    }
                });

            }
        });
        button_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isAllSpace(content)&&selectedPhotos.size()==0){//如果都是空的，直接退出好了
                    finish();
                }else {
                    AlertDialog alert = new AlertDialog.Builder(addDynamic_Activity.this).create();
                    // alert.setIcon(R.drawable.stop);
                    // alert.setTitle("返回？");
                    alert.setMessage("取消将丢失已经编辑的内容");
                    //添加取消按钮
                    alert.setButton(DialogInterface.BUTTON_NEGATIVE, "继续编辑", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    //添加"确定"按钮
                    alert.setButton(DialogInterface.BUTTON_POSITIVE, "仍要返回", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            finish();
                        }
                    });
                    alert.show();
                }
            }
        });
        button_addDynamic.setClickable(false);


        sweetAlertDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        sweetAlertDialog.setTitleText("上传中,请稍后");
        sweetAlertDialog.setCancelable(false);
        sweetAlertDialog.dismiss();
    }

    //判断是否全部都是空格，是则范围true
    private boolean isAllSpace(String s){
        if(s==null){
            return true;
        }
        char[] arrays = s.toCharArray();
        int num=0;
        for (int i=0;i<s.length();i++){
            if(arrays[i]==' '){
                num++;
            }
        }
        return num==s.length();
    }

    static int comPressNum;
    private String[] compressPictures(final String[] paths){

        final String[] newPath=new String[paths.length];
        for (int i=0;i<paths.length;i++){
            newPath[i]=getExternalCacheDir()+"/dynamic"+i+".jpg";

            new compressPicturesTask(new compressPicturesListener() {
                @Override public void onProgress(int progress) {}
                @Override public void onFailed() {}

                @Override
                public void onSuccess() {
                    comPressNum++;
                    if(comPressNum==paths.length){
                        comPressNum=0;


                        BmobFile.uploadBatch(newPath, new UploadBatchListener() {
                            @Override
                            public void onSuccess(List<BmobFile> list, List<String> urls) {

                                if(urls.size()==newPath.length){//如果数量相等，则代表文件全部上传完成

                                    alumniCircle.setPhoto(urls);
                                    alumniCircle.setPhotoNumber(urls.size());
                                    alumniCircle.update(objectId, new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            if(e==null){
                                                //发送成功，可以结束活动
                                                Intent intent = new Intent();
                                                intent.putExtra("data_return", "success");
                                                setResult(RESULT_OK, intent);
                                                //移除progress
                                                sweetAlertDialog.dismiss();
                                                finish();
                                            }else{
                                                Toast.makeText(addDynamic_Activity.this,"图片更新失败"+e.getMessage(),Toast.LENGTH_LONG).show();
                                                button_addDynamic.setClickable(true);
                                            }
                                        }
                                    });
                                }
                            }
                            @Override
                            public void onProgress(int i, int i1, int i2, int i3) {
                                //1、curIndex--表示当前第几个文件正在上传
                                //2、curPercent--表示当前上传文件的进度值（百分比）
                                //3、total--表示总的上传文件数
                                //4、totalPercent--表示总的上传进度（百分比）

                            }
                            @Override
                            public void onError(int i, String s) {
                                Toast.makeText(addDynamic_Activity.this,"图片上传失败："+s,Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }

            }).execute(paths[i],newPath[i],"10240");
        }
        return newPath;
    }



    private class GridAdapter extends BaseAdapter {
        public final static int TYPE_ADD = 1;
        public final static int TYPE_PHOTO = 2;
        public final static int MAX = 9;




        @Override
        public int getItemViewType(int position) {
            return (position == selectedPhotos.size() && position != MAX) ? TYPE_ADD : TYPE_PHOTO;
        }
        @Override
        public int getCount() {
            //return listUrls.size();
            int count = selectedPhotos.size() + 1;
            if (count > MAX) {
                count = MAX;
            }
            return count;
        }

        @Override
        public String getItem(int position) {
            return selectedPhotos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if(getItemViewType(position)==TYPE_PHOTO) {
               // if (convertView == null) {
                    convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                    imageView = (ImageView) convertView.findViewById(R.id.imageView);
                    convertView.setTag(imageView);
                    // 重置ImageView宽高
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
                    imageView.setLayoutParams(params);
            //    } else {
            //        imageView = (ImageView) convertView.getTag();
            //    }
                final RequestOptions options = new RequestOptions();
                options.centerCrop()
                        .placeholder(me.iwf.photopicker.R.drawable.__picker_ic_photo_black_48dp)
                        .error(me.iwf.photopicker.R.drawable.__picker_ic_broken_image_black_48dp);
                Glide.with(addDynamic_Activity.this)
                        .load(new File(getItem(position)))
                        .apply(options)
                        .thumbnail(0.1f)
                        .into(imageView);


            }else {
             //   if (convertView == null) {
                    convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                    imageView = (ImageView) convertView.findViewById(R.id.imageView);
                    convertView.setTag(imageView);
                    // 重置ImageView宽高
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
                    imageView.setLayoutParams(params);

            //    }else {
            //        imageView = (ImageView) convertView.getTag();
            //    }
                imageView.setBackgroundResource(com.example.pei.papa.R.drawable.addphoto);

            }
            return convertView;
        }
    }

}
